/* eslint-disable no-param-reassign */
<template>
  <div class="examMgn">
    <GeminiScrollbar class="container" @ready="initScrollbar" :autoshow="true">
      <div class="table-header">
        <p>试卷列表</p>
        <div class="search-bar">
          <input v-model="name" type="text" placeholder="试卷标题" @keyup.enter="findPos">
          <div class="btn primary" style="margin-right:5px" @click="findExam">搜索</div>
          <div class="btn primary" @click="addPositionClicked">添加</div>
        </div>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th></th>
            <th>试卷标题</th>
            <th>试题数量</th>
            <th>创建时间</th>
            <th>当前状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <template v-for="(pos, index) of tableData">
            <tr :key="pos.id">
              <td class="expend">
                <img
                  :class="{ rotate: nowExpend === index }"
                  @click="expend(index, pos.id)"
                  src="@/assets/img/u4210.png"/>
              </td>
              <td>{{ pos.name }}</td>
              <td>{{ pos.count }}</td>
              <td>{{ new Date(pos.createDate).Format('yyyy-MM-dd') }}</td>
              <td :class="{
                success: pos.status === '1',
                warn: pos.status === '0'
              }" v-if="pos.status === '1'">已启用</td>
              <td :class="{
                success: pos.status === '1',
                warn: pos.status === '0'
              }" v-if="pos.status === '0'">已停用</td>
              <td style="text-align:left;width:145px">
                <a v-if="pos.status === '1'" @click="changeStatus(pos.id, '0', pos.count)">停用</a>
                <a v-if="pos.status === '0'" @click="changeStatus(pos.id, '1', pos.count)">启用</a>
                <a v-if="pos.count === 0" @click="assign(pos.id)">配置</a>
                <a @click="deletePos(pos.id)">删除</a>
                <a @click="download(pos.id)">下载</a>
              </td>
            </tr>
            <tr :key="pos.id + 10000" v-show="nowExpend === index">
              <td class="middle" colspan="7">
                <div class="middle-container" colspan="7">
                  <div class="box">
                    <p class="title">试卷信息</p>
                    <p v-if="msg">{{ msg }}</p>
                    <VeHist
                      v-if="!msg"
                      width="250px"
                      height="400px"
                      :extend="{
                        series: {
                          barWidth: 30,
                        }
                      }"
                      :legend-visible="false"
                      :data="chartData1"
                      :settings="chartSettings1"
                      :ref="`chart${index}`"></VeHist>
                    <VeHist
                      v-if="!msg"
                      width="550px"
                      height="400px"
                      :extend="{
                        series: {
                          barWidth: 30,
                        }
                      }"
                      :legend-visible="false"
                      :data="chartData2"
                      :settings="chartSettings2"
                      :ref="`chart${index}`"></VeHist>
                      <p class="title">试卷描述</p>
                      {{ pos.desc }}
                  </div>
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>
    </GeminiScrollbar>
    <footer>
      <Page @setCurPage="setCurPage" :curPage="curPage" :total="total" :pageSize="pageSize"></Page>
    </footer>
    <position-dialog
      @close="addPositionShow = false"
      @done="addPosition"
      :dialogData="{}"
      title="添加试卷"
      :show="addPositionShow"
    ></position-dialog>
    <position-dialog
      @close="modifyPositionShow = false"
      @done="modifyPosition"
      :dialogData="modifyPositionData"
      title="修改试卷信息"
      :show="modifyPositionShow"
    ></position-dialog>
  </div>
</template>
<script>
import VeHist from 'v-charts/lib/histogram.common';
/* eslint-disable no-param-reassign */
import Page from '@/components/Pages/index';
import PositionDialog from '@/components/Dialogs/addExam';
import api from '@/api/examMgn';

async function getExam(curPage, name) {
  const tableData = [];
  const params = new URLSearchParams();
  params.append('companyId', sessionStorage.getItem('companyId'));
  params.append('name', name);
  params.append('rows', 10);
  params.append('page', curPage);
  const response = await api.getExamApi(params);
  const datas = response.data.rows;
  const total = response.data.total;
  for (let i = 0; i < datas.length; i += 1) {
    tableData.push({
      id: datas[i].examId,
      name: datas[i].examTitle,
      createDate: datas[i].createDate,
      desc: datas[i].examDescription,
      count: datas[i].examQuestionCount,
      status: datas[i].examStatus,
    })
    ;
  }
  return [total, tableData];
}
export default {
  name: 'examMgn',
  data() {
    return {
      nowExpend: -1,
      name: '',
      tableData: [],

      curPage: 1,
      total: 1000,
      pageSize: 10,

      addPositionShow: false,
      modifyPositionShow: false,
      modifyPositionData: null,

      seeShow: false,
      scrollObj: null,

      // extend: {
      //   series: {
      //     label: { show: true, position: 'top' },
      //   },
      // },
      chartSettings1: {
        yAxisType: ['percent'],
        max: [1],
        min: [0],
        itemStyle: {
          color: '#0064D3',
        },
      },
      chartData1: {
        columns: ['x', '数值'],
        rows: [
          { x: '试卷难度', 数值: 0.6 },
          { x: '区分度', 数值: 0.2 },
          { x: '信度', 数值: 0.8 },
        ],
      },

      chartSettings2: {
        itemStyle: {
          color: '#0064D3',
        },
        max: [100],
        min: [0],
        barWidth: '10',
      },
      chartData2: {
        columns: ['x', '数值'],
        rows: [
          { x: '平均分', 数值: 0.6 },
          { x: '方差', 数值: 0.2 },
          { x: '高分组均分', 数值: 0.8 },
          { x: '低分组均分', 数值: 0.8 },
        ],
      },
      msg: null,
    };
  },
  beforeRouteEnter(to, from, next) {
    if (sessionStorage.getItem('userToken') === null) {
      next({ path: '/login' });
    }
    getExam(1, '').then((jobs) => {
      next((vm) => {
        vm.$emit('route-switch', window.location.href.split('/').pop());
        vm.total = jobs[0];
        vm.tableData = [...jobs[1]];
      });
    });
  },
  methods: {
    download(id) {
      window.location.href = `http://123.206.41.36:8080/bexam/getRealPaperWoAu?examId=${id}`;
    },
    async setCurPage(page) {
      this.curPage = page;
      const jobs = await getExam(page, this.name);
      this.total = jobs[0];
      this.tableData = [...jobs[1]];
    },
    async expend(index, id) {
      if (this.nowExpend === index) {
        this.nowExpend = -1;
        return;
      }
      const total = await api.getStatisticTotal(id);
      const allQues = await api.getStatistic(id);
      // 单题分数
      const singleMark = 100 / allQues.data.data.questionStatisticsList.length;
      // 总人数
      const totalPeople = total.data.data.totalPeople;
      if (totalPeople === 0) {
        this.msg = '完成人数不具有统计学意义，需要更多的人完成试卷';
      } else {
        this.msg = null;
      }
      // 题目总方差
      let queTotalVariance = 0;
      allQues.data.data.questionStatisticsList.forEach((e) => {
        queTotalVariance += e.variance;
      });
      // 信度
      const reliability = (totalPeople / (totalPeople - 1)) *
      (1 - (queTotalVariance.toFixed(2) / total.data.data.variance.toFixed(2)));

      // 题目难度--前27%
      const queDifficultyBefore27Avg = [];
      const before27TotalPeople = Math.round((totalPeople * 0.27));
      allQues.data.data.questionStatisticsList.forEach((e) => {
        const wrongPeople = (before27TotalPeople / singleMark) * (singleMark - e.before27Avg);
        if (e.questionType === '2') {
          const difficulty = 1 - (wrongPeople / before27TotalPeople);
          queDifficultyBefore27Avg.push(difficulty);
        } else {
          // 选择题 答案永远是4个
          const difficulty = ((4 * (before27TotalPeople - wrongPeople)) - before27TotalPeople) /
          (before27TotalPeople * 3);
          queDifficultyBefore27Avg.push(difficulty);
        }
      });

      // 题目难度--后27%
      const queDifficultyAfter27Avg = [];
      const after27TotalPeople = Math.round((totalPeople * 0.27));
      allQues.data.data.questionStatisticsList.forEach((e) => {
        const wrongPeople = (after27TotalPeople / singleMark) * (singleMark - e.after27Avg);
        if (e.questionType === '2') {
          const difficulty = 1 - (wrongPeople / after27TotalPeople);
          queDifficultyAfter27Avg.push(difficulty);
        } else {
          // 选择题 答案永远是4个
          const difficulty = ((4 * (after27TotalPeople - wrongPeople)) - after27TotalPeople) /
          (3 * after27TotalPeople);
          queDifficultyAfter27Avg.push(difficulty);
        }
      });
      // 试卷信度
      let realiability = 1 / 100;
      let sum = 0;
      for (let i = 0; i < queDifficultyBefore27Avg.length; i += 1) {
        sum += (queDifficultyBefore27Avg[i] - queDifficultyAfter27Avg[i]) * singleMark;
      }
      realiability *= sum;

      this.chartData1.rows = [
        { x: '试卷难度', 数值: total.data.data.totalAvg / 100 },
        { x: '区分度', 数值: realiability },
        { x: '信度', 数值: reliability },
      ];
      this.chartData2.rows = [
        { x: '平均分', 数值: total.data.data.totalAvg },
        { x: '标准差', 数值: total.data.data.standard },
        { x: '高分组均分', 数值: total.data.data.before27Avg },
        { x: '低分组均分', 数值: total.data.data.after27Avg },
      ];
      this.nowExpend = index;
      this.$nextTick(() => {
        this.$refs[`chart${index}`][0].echarts.resize();
        this.scrollObj.update();
      });
    },
    addPositionClicked() {
      this.addPositionShow = true;
    },
    see() {
      this.seeShow = true;
    },
    addPosition(pos) {
      this.addPositionShow = false;
      const params = new URLSearchParams();
      params.append('companyId', sessionStorage.getItem('companyId'));
      params.append('title', pos.name);
      params.append('description', pos.desc);
      params.append('status', '0');
      api.addApi(params).then(async (response) => {
        if (response.data.code === 200) {
          this.$alert('添加成功');
          const jobs = await getExam(this.curPage, this.name);
          this.total = jobs[0];
          this.tableData = [...jobs[1]];
        } else {
          this.$alert(response.data.message);
        }
      });
    },
    modifyPositionClicked(pos) {
      this.modifyPositionShow = true;
      this.modifyPositionData = { ...pos };
    },
    modifyPosition(pos) {
      this.modifyPositionShow = false;
      const params = new URLSearchParams();
      params.append('name', pos.name);
      params.append('description', pos.desc);
      api.updateApi(pos.id, params).then(async (response) => {
        if (response.data.code === 200) {
          this.$alert('修改成功');
          const jobs = await getExam(this.curPage, this.name);
          this.total = jobs[0];
          this.tableData = [...jobs[1]];
        } else {
          this.$alert(response.data.message);
        }
      });
    },
    changeStatus(posId, status, count) {
      if (count === 0) {
        this.$alert('没有题目的试卷不可被启用');
        return;
      }
      this.$confirm('确定要改变状态吗?', (res) => {
        if (res) {
          const params = new URLSearchParams();
          params.append('status', status);
          api.updateApi(posId, params).then(async (response) => {
            if (response.data.code === 200) {
              this.$alert('修改成功');
              const jobs = await getExam(this.curPage, this.name);
              this.total = jobs[0];
              this.tableData = [...jobs[1]];
            } else {
              this.$alert(response.data.message);
            }
          });
        }
      });
    },
    assign(p) {
      this.$router.push({ name: 'QuestionAssign', query: { examId: p } });
    },
    deletePos(posId) {
      this.$confirm('确定要删除该试卷吗?', (res) => {
        if (res) {
          api.deleteApi(posId).then(async (response) => {
            if (response.data.code === 200) {
              this.$alert('删除成功');
              const jobs = await getExam(this.curPage, this.name);
              this.total = jobs[0];
              this.tableData = [...jobs[1]];
            } else {
              this.$alert(response.data.message);
            }
          });
        }
      });
    },
    async findExam() {
      const jobs = await getExam(this.curPage, this.name);
      this.total = jobs[0];
      this.tableData = [...jobs[1]];
    },
    initScrollbar(bar) {
      this.scrollObj = bar;
    },
  },
  components: {
    Page,
    PositionDialog,
    VeHist,
  },
};
</script>
<style lang="less">
@import url(../../../../static/style/site.comm.less);
@import url(../../../../static/style/site.vars.less);

.examMgn {
  background: #fff;
  box-shadow: 0 3px 6px rgba(6,0,1,.05);
  &>.container {
    position: relative;
    height: 701px;
    overflow-y: scroll;
    &::-webkit-scrollbar {
      display: none;
    }
    .table-header {
      position: sticky;
      top: 0;
    }
    .middle {
      background: rgba(216, 229, 255, 0.397);
      .middle-container {
        padding: 20px 100px;
        text-align: left;
        // display: flex;
        // justify-content: flex-start;
        .box {
          // width: 30%;
          margin-right: 30px;
          padding: 10px;
          .ve-histogram {
            display: inline-block;
            margin-right: 70px;
          }
        }
        p {
          margin: 10px 0;
        }
        .title, .que-title {
          font-size: 16px;
          font-weight: 600;
          margin-right: 10px;
          position: relative;
          user-select: none;
        }
        .title::before {
          content: "";
          position: absolute;
          width: 3px;
          height: 15px;
          border-radius: 10px;
          background-color: @site-main;
          left: -10px;
          top: 3.5px;
        }
      }
    }
  }
  & > footer {
    padding: 20px 0 20px 0;
    width: 100%;
    background: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
  }
}
</style>
